package com.hongawen.unsafe;

import lombok.SneakyThrows;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年09月01日 15:26
 */
public class Counterss {

    @SneakyThrows
    public static void main(String[] args) {
        Counters t1 = new Counters();
        Counters t2 = new Counters();
        new Thread(() -> t1.add(100)).start();
        new Thread(() -> t1.dec(100)).start();

        new Thread(() -> t2.add(100)).start();
        new Thread(() -> t2.dec(100)).start();
        Thread.sleep(1000);
        System.out.println("t1.count = " + t1.get());
        System.out.println("t2.count = " + t2.get());
    }
}

class Counters {

    private int count = 0;

    @SneakyThrows
    public synchronized void add(int n) {
        Thread.sleep(5000);
        count += n;
    }

    public synchronized void dec(int n) {
        count -= n;
        System.out.println(Thread.currentThread().getName()+":"+count);
    }

    public int get() {
        return count;
    }
}